package com.fpost.action;

import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.TimeZone;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.fpost.constants.ActionConstants;
import com.fpost.form.MainForm;
import com.fpost.util.ArticleUtils;
import com.fpost.util.CommonUtils;
import com.fpost.util.DateUtil;

public class MainAction extends Action {
	
	private static Logger log = Logger.getLogger(MainAction.class);

	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		
		//set current path in session
		CommonUtils.setCurrentPathInSession(request, mapping);
		
		String forward = ActionConstants.SUCCESS;
		MainForm mainForm = (MainForm)form;	
		
//		long startTime = System.currentTimeMillis();		

		mainForm.setMostRecentArticles(ArticleUtils.getMostRecentCurrentArticles(ActionConstants.MAX_RECENT_RESULTS));

//		String methodName = "MainAction execute(): ";
//		System.out.println(methodName + "time0: " + (System.currentTimeMillis() - startTime));
//		startTime = System.currentTimeMillis();
		
		mainForm.setMostPopularArticles(ArticleUtils.getMostPopularCurrentArticles(ActionConstants.MAX_POPULAR_RESULTS));		
		
//		System.out.println(methodName + "time1: " + (System.currentTimeMillis() - startTime));
//		startTime = System.currentTimeMillis();
		
		Calendar calendar = DateUtil.getGMTCalendar();
		calendar.add(Calendar.YEAR, -1);
		System.out.println("calendar date = [" + calendar.getTime() + "]");
		
		java.sql.Date from = new java.sql.Date(calendar.getTimeInMillis());
		java.sql.Date to = new java.sql.Date(System.currentTimeMillis());
		System.out.println("to="+to.toString());
		mainForm.setArticlesWithHighestRating(ArticleUtils.getHighestRatingCurrentArticles(from, to, ActionConstants.MAX_HIGHEST_RATING_RESULTS));
//		System.out.println(methodName + "time2: " + (System.currentTimeMillis() - startTime)); 
		
		//mainForm.setMaxRecentResults(ActionConstants.MAX_RECENT_RESULTS);
		//mainForm.setMaxPopularResults(ActionConstants.MAX_POPULAR_RESULTS);
		//mainForm.setMaxHighestResults(ActionConstants.MAX_HIGHEST_RATING_RESULTS);
		
		return mapping.findForward(forward);
	}
	

}
